(function() {
	var skill = {
		save: function() {
			delete this.card_cash_map
			delete this.card_factory_map
			db.update(config.dbname.goods, this._id, this);
		},
		destroy: function() {
			db.remove(config.dbname.goods, this._id);
		},
		//非安全
		_setInfo: function(goods_info) {
			/*
			 * TODO:填平参数
			 */
			this._initInfo(goods_info);
			this.save();
			return this._id;
		},
		//获取可访问的地址
		getUrl: function(base_url) {
			if (!base_url) {
				var bus = BusCon.get(this.bus_id);
				base_url = bus.getOneVisitableUrl()
			}
			return base_url + "/goods-details.html?id=" + this._id;
		},
		//非安全，批量修改商品信息
		_initInfo: function(info) {
			var self = this;
			var goods_name = (info.name || info.goods_name || "").trim();
			if (!goods_name) {
				throwCusError("商品名称不可为空")
			}
			//商品名称
			if (!helper.folder_name(goods_name)) {
				throwCusError("商品名命名不规范")
			}
			self.goods_name = goods_name;
			//商品介绍
			self.intro = info.intro ? String(info.intro) : "";
			if (self.intro.length > config.leagueDescriptionLength) {
				throwCusError("商品简介长度超出长度限制");
			}
			//所需现金（基础现金）
			info.price || (info.price = info.price === 0 ? "0" : "");
			if (!info.price) {
				throwCusError("商品价格不可为空")
			}
			self.price = +(info.price + "").replace(/[^0-9\.]/ig, "");
			if (isNaN(self.price)) {
				throwCusError("错误的价格信息")
			}
			//所需积分（基础积分）
			self.integral = parseFloat(info.integral) || 0;
			//所需运费（基础运费）
			self.fare = parseFloat(info.fare) || 0;

			//原价
			self.original_price = parseFloat(info.original_price) || 0;

			//VIP价
			self.vip_price = parseFloat(info.vip_price) || 0;

			//最终花销
			self.cash = 0;

			//返现，和推荐返利不同，这个返现直接到账户余额上
			self.back_cash = parseFloat(info.back_cash) || 0;

			if (self.back_cash) { //如果有返现，则添加返现buff
				var back_cash_buff_id = self.back_cash_buff_id;
				if (back_cash_buff_id) {
					var back_cash_buff = BuffCon.get(back_cash_buff_id);
				} else {
					back_cash_buff = new BuffCon({
						name: "商品返现",
						code_id: "商品返现",
						config: {
							goods_id: self._id
						}
					});
					back_cash_buff_id = self.back_cash_buff_id = back_cash_buff._id;
				}
				back_cash_buff.config.back_cash = self.back_cash;
				self._addBuff(back_cash_buff_id);
			} else {
				self.back_cash_buff_id && self._removeBuff(self.back_cash_buff_id);
			}

			//预览图的路径
			self.preview_img_url = info.preview_img_url;
			//详情图
			self.detail_img_urls = info.detail_img_urls || [];
			if (self.detail_img_urls.length > config.storeImagesNumber) {
				throwCusError("商品详情图数量过多")
			}
			//自定义分类
			/*无需再另外使用一个类
	{
		class_name:"颜色"
		class_itmes:[{
			name:"红",
			bg_url:"[/comment_img/red.jpg]",
			price_change:"+10",
			fare_change:"-0.5",
			num:10//库存
		}],
		default_item:"红"
	}
			*/
			self.classification = info.classification || [];
			//限购量
			self.limit = info.limit || Number.MAX_VALUE;
			//库存量
			if (typeof info.num !== "number") {
				info.num || (info.num = "0");
				info.num = String(info.num);
				var _num = info.num.replace(/[^0-9\.]/ig, "");
			} else {
				_num = info.num;
			}
			self.num = +_num;
			//单位
			if (isNaN(self.num)) {
				throwCusError("错误的商品单位");
			}
			self.unit = (info.unit || "").trim() || String(info.num).replace(_num, "").trim() || "件";

			//PS：带权限的属性，不能直接获取，需要经过商家的权限判定才能使用
			//是否是虚拟商品
			self.is_virtual = helper.boolean_parse(info.is_virtual);
			//PS：同上
			//是否只能用在线支付
			self.only_online_pay = helper.boolean_parse(info.only_online_pay);

			//运费模板，为空则意味着 商家承担运费
			self.express_id = info.express_id || "";

			//商品详情
			self.detail_content = helper.xss(info.detail_content);

			self.goods_args_map_id = GoodsArgsMapCon.get(info.goods_args_map_id) ? info.goods_args_map_id : undefined;
			if (self.goods_args_map_id) {
				self.using_goods_args = Array.isArray(info.using_goods_args) ? info.using_goods_args : []
			}


			//商品类目
			if (self.classify_id !== info.classify_id) {
				self._setClassify(info.classify_id);
			}
			// //脚本过滤
			// .replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,"")
			// .replace(/<script[^>]*>([\s\S]*?)/gi,"")//防止自动闭合的标签
			// //输入框过滤
			// .replace(/<input/gi,"<fuck-input")
			// .replace(/<\/input/gi,"</fuck-input")
			// //url过滤
			// .replace(/javascript\:/ig,"")
			// //事件过滤
			// .replace(/on[\w\W\s]+?=/ig,"fuck-on=")
			;
		},
		//非安全，减少库存增加销量
		_cutNum: function(sale_num) {
			var num = (this.num || 0) - sale_num;
			if (num < 0) {
				throwCusError("商品库存不足");
			}
			var sale_num = (this.sale_num || 0) + sale_num;
			this.sale_num = sale_num;
			this.num = num;
			this.save();
		},
		//非安全，返还库存返回销量
		_returnNum: function(sale_num) {
			var num = (this.num || 0) + sale_num;
			var sale_num = (this.sale_num || 0) - sale_num;
			this.sale_num = sale_num;
			this.num = num;
			this.save();
		},
		//获取销量
		getSaleNum: function() {
			return this.sale_num || 0;
		},
		//非安全，改变库存量
		_setNum: function(num) {
			this.num = num;
			this.save();
		},
		// 非安全，增加库存
		_addNum: function(num) {
			num = ~~num;
			if (num <= 0) {
				throwCusError("商品新增库存数量有误")
			}
			this.num += num;
			this.save();
		},
		//非安全，直接从一个商品生成订单
		//return ach_id
		_toAch: function(info /*user_id,user_address_id,num*/ ) {
			var user_id = info.user_id;
			var user_address_id = info.user_address_id;
			// console.log(info,user_address_id);
			var num = Math.abs(parseInt(info.num)) || 1;
			var recommender_id = info.recommender_id;
			var guide_id = info.guide_id;
			var pay_method = info.pay_method;
			var ach = new AchCon({
				//类，构造器名字
				type: "goods",
				//缓存商品信息，力保届时可以还原页面访问的情形
				goods_info: [{
					goods_id: this._id,
					//商品数量
					num: num
				}],
				user_id: user_id,
				bus_id: this.bus_id,
				recommender_id: recommender_id,
				guide_id: guide_id,
				user_address_id: user_address_id,
				//订单的独立BUFF
				buffs: [],
				state: AchCon.STATE.未付款,
				pay_method: pay_method,
			});
			return ach._id;
		},
		getDetail: function() {
			var goods = $Object.clone(this);
			goods.evaluations = this.getEvaluations();
			return goods;
		},
		getCommentList: function(num, page) {
			var comments = this.comments || (this.comments = []);
			comments = data_cut.page(comments, num, page)
			comments.forEach(function(commnet_id, index) {
				comments[index] = CommentCon.get(commnet_id);
			});
			return comments;
		},
		//添加评价，非安全
		_addEvaluation: function(evaluation_id) {
			var evaluations = this.evaluations || (this.evaluations = []);
			evaluations.push(evaluation_id);
			this.save();
		},
		//获取详细评价，包括评价的子评论
		getEvaluations: function(num, page) {
			var evaluations = this.evaluations || (this.evaluations = []);
			evaluations = data_cut.page(evaluations, num, page);
			evaluations = evaluations.map(function(evaluation_id, index) {
				var evaluation = EvaluationCon.get(evaluation_id);
				return evaluation.getDetail();
			});
			return evaluations;
		},
		//获取标签
		//无需分页功能
		getTags: function() {
			var tags = (this.tags || []).slice();
			tags.forEach(function(tag_id, index) {
				tags[index] = TagCon.get(tag_id);
			});
			return tags;
		},
		//非安全，添加标签
		_addTag: function(tag_id) {
			var tags = this.tags || (this.tags = []);
			if (tags.indexOf(tag_id) === -1) {
				tags.push(tag_id);
				this.save();
			}
		},
		//非安全，删除标签
		_removeTag: function(tag_id) {
			var tags = this.tags || (this.tags = []);
			var index = tags.indexOf(tag_id);
			if (index === -1) {
				throwCusError("商品不属于指定标签");
			}
			tags.splice(index, 1);
			this.save();
		},
		//非安全，移动到指定文件夹或者滞空
		_setClassify: function(classify_id) {
			var old_classify_id = this.classify_id;
			if (old_classify_id) {
				var old_classify = ClassifyCon.get(old_classify_id);
				try { //错误不抛出
					old_classify._removeGoods(this._id);
				} catch (e) {
					console.error("ERROR IN:_setClassify")
					console.error(e)
					console.error("----")
				}
			}
			var classify = ClassifyCon.get(classify_id);
			if (classify) {
				// 无需抛出错误
				classify._addGoods(this._id);
			}
			this.classify_id = classify && classify._id;
			this.save();
		},
		//重置金额
		_initCash: function() {
			this.cash = +this.price;
			this.card_cash_map = {};
			this.express_price = this.getExpressPrice();
			this.save();
		},
		getExpressPrice: function() {
			var express_id = this.express_id;
			if (express_id) {
				try {
					var bus = BusCon.get(this.bus_id);
					return bus._getExpress(express_id).express_price;
				} catch (e) {}
			}
			return 0;
		},
		getCash: function(buffEnv, callBy, other_args) {
			this._initCash();
			buffEnv || (buffEnv = BuffCon.env.showing);
			callBy || (callBy = "goods_getCash");
			this.emitBuffs(buffEnv, callBy, other_args);
			return this.cash;
		},
		isUnSold: function() {
			var bus = BusCon.get(this.bus_id);
			return bus._getUnSoldGoods().indexOf(this._id) !== -1
		}
	};
	module.exports = skill.multiInherits(
		require("./skill.goods_args_map"),
		require("./skill.buff"),
		require("./skill.extend.bina"),
		require("./skill.card_factory")
	);

	var db = require("../db/index");
	var config = require("../_include/config");
	var GoodsArgsMapCon = require("../goods_args_map/_con");
	var UserAddressCon = require("../user_address/_con");
	var AchCon = require("../ach/_con");
	var data_cut = require("../_include/data_cut");
	var CommentCon = require("../comment/_con");
	var EvaluationCon = require("../eval/_con");
	var ClassifyCon = require("../bus.classify/_con");
	var TagCon = require("../bus.tag/_con");
	var BusCon = require("../bus/_con");
	var ExpressCon = require("../bus.express/_con");
	var BuffCon = require("../buff/_con");
	var buffCode = require("../buff/buff_code");
	var $Object = require("../_include/$.Object");
	var helper = require("../_include/helper");
	var xss = require("xss");


}());